import { ElMessageBox, ElMessage } from "element-plus";
import { addProductAdd } from "@/api/modules/agv";
import { useBeforeUnload } from "@/hooks/useBeforeUnload";
import { useUtils } from "./useUtils";
import { generateUUID } from "@/utils";
import { useTabsStore } from "@/stores/modules/tabs";

import { useRoute, useRouter } from "vue-router";
export const useAdd = (options: any) => {
  const { formData, selectList, appearance, testVideo, rules } = options; //  ruleFormRef,
  const { transformDataReq, productBaseData } = useUtils();
  const tabStore = useTabsStore();
  const router = useRouter();
  const route = useRoute();

  const initData = async () => {
    appearance.value = [];
    testVideo.value = [];
    const { result, appearanceTestVideo, keyPart } = await productBaseData({ selectList });
    // 获取传输的值
    for (const [key, value] of Object.entries(appearanceTestVideo)) {
      value.forEach((item: any) => {
        result[item.id].forEach((item2: any) => {
          formData.value["productDataList"].push({
            id: "",
            category: key,
            categorySub: item.id,
            remark: item2.name,
            type: item2.value,
            path: "",
            uuid: item2.id,
            fixed: 1, // 是否固定
            lonely: 1 // 是否独立上传
          });
        });
      });
    }
    // 图片外观 、 测试视频页面结构
    Object.keys(appearanceTestVideo)
      .reverse()
      .forEach((item, index) => {
        const list = formData.value["productDataList"].filter((itm: any) => itm.category == item);
        switch (index) {
          case 0:
            appearanceTestVideo[item].forEach((item2: any) => {
              item2.productDataList = list.filter((itm: any) => itm.categorySub == item2.id);
              appearance.value.push(item2);
            });
            break;
          case 1:
            appearanceTestVideo[item].forEach((item2: any) => {
              item2.productDataList = list.filter((itm: any) => itm.categorySub == item2.id);
              testVideo.value.push(item2);
            });
            break;
        }
      });

    // 关键零部件
    Object.keys(keyPart).forEach(item => {
      item &&
        keyPart[item].forEach((item2: any) => {
          formData.value["productParts"].push({
            id: "",
            remark: "",
            partTypeId: item2.param,
            partId: "",
            partName: "",
            code: "",
            type: 1,
            path: "",
            uuid: generateUUID(),
            fixed: 1, // 是否固定
            lonely: 1 // 是否独立上传
          });
        });
    });
  };
  const handleSubmit = async () => {
    // ruleFormRef.value!.validate(async (valid: Boolean, errors: any) => {
    //   console.log(errors);
    //   if (!valid) return;
    // });
    try {
      for (const [key, value] of Object.entries(rules.value)) {
        if (!formData.value[key]) {
          console.log(key, value);
          ElMessage({
            message: value[0]["message"],
            type: "error"
          });
          return;
        }
      }

      await addProductAdd(transformDataReq(formData.value, appearance.value, testVideo.value));
      ElMessage.success({ message: `新增车辆成功！` });
      tabStore.removeTabs(route.fullPath);
      router.push("/agv/index");
    } catch (error) {
      console.log(error);
    }
    // });
  };

  const handleCancel = () => {
    ElMessageBox.confirm(`是否有数据未保存，确认取消吗?`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    }).then(() => {
      tabStore.removeTabs(route.fullPath);
      router.push("/agv/index");
    });
  };
  useBeforeUnload();
  return {
    handleSubmit,
    initData,
    handleCancel
  };
};
